package pri.zxx.webdemo.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import pri.zxx.webdemo.utils.GsonUtil;

import jakarta.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;

@Aspect
@Component//定义一个切面
public class LogRecordAspect {
    private static final Logger logger = LoggerFactory.getLogger(LogRecordAspect.class);
    public final String string = "execution(*  *..*.*.controllers..*.*(..))";

    // 定义切点Pointcut
    @Pointcut(value = string)
    public void executeService() {
    }

    // 通知（环绕）
    @Around("executeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {

        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
//        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        Object[] args = pjp.getArgs();
        String params = "";
        // result的值就是被拦截方法的返回值
        long startTime = System.currentTimeMillis();
        Object result = pjp.proceed();
        long endTime = System.currentTimeMillis();
        try {
            //获取请求参数集合并进行遍历拼接
            if (args.length > 0) {
                if ("POST".equals(method)) {
                    Object object = args[0];
                    params = GsonUtil.toJson(object);
                } else if ("GET".equals(method)) {
                    params = queryString;
                }
                if (!StringUtils.isEmpty(params)) {
                    params = URLDecoder.decode(params, StandardCharsets.UTF_8.name());
                }
            }
            LinkedHashMap<String, Object> mp = new LinkedHashMap<>();
            mp.put("请求地址", uri);
            mp.put("请求参数", params);
            mp.put("处理时间", (endTime - startTime) / 1000 + "s");
            mp.put("请求类型", method);
            mp.put("请求方法", ((MethodSignature) pjp.getSignature()).getMethod().getName());
            logger.warn("请求:{}", GsonUtil.toJson(mp));
        } catch (Exception e) {
            logger.error("log error !!", e);
        }
        return result;
    }


}
